package com.itboye.sunsun.luntan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.homesensen.alert.ByAlert;
import com.itboye.sunsun.adapter.JingHuaTieAdapter;
import com.itboye.sunsun.adapter.LunTanDetailAdapter;
import com.itboye.sunsun.adapter.LunTanTwoDetailAdapter;
import com.itboye.sunsun.beans.LunTanHomePageBean;
import com.itboye.sunsun.beans.LunTanHomePageBean.LunTanItemBean;
import com.itboye.sunsun.beans.LuntanForumBean;
import com.itboye.sunsun.beans.LuntanForumBean.LuntanForumItemBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.luntan.news.RichTextActivity;
import com.itboye.sunsun.luntan.tabadapters.PagerAdapter;
import com.itboye.sunsun.luntan.tabadapters.ScrollTabsAdapter;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;
import com.umeng.socialize.utils.Log;

import java.util.ArrayList;
import java.util.List;

public class LunTanDetailActivity extends BaseActivity implements
		OnClickListener {

	XListView xlistview;
	TextView title;
	String fid;
	private int pageNum = 1;
	ImageView back, edit;
	BaseAdapter adapter;
	String subforum;
	List<LunTanItemBean> dataList = new ArrayList<>();

	List<LunTanItemBean> dataListtwo = new ArrayList<>();

	LunTanTwoDetailAdapter detailAdapter;
	private ScrollTabView tabs;
	private ScrollTabsAdapter tabsAdapter;
	private ViewPager viewpager;
	JingHuaTieAdapter huaTieAdapter;
	protected ArrayList<LuntanForumItemBean> arrayListForm;
	FrameLayout in;
	public static String CLOSELUNTANDETAIL = "exit";
	public static String ffid;

	private ImageView imgTop, shuizu_more;
	PopupWindow popupWindow;
	private int isButton = 0;
	private int digest;
	protected boolean isJingHua;
	private RelativeLayout re_shuizu_search;
	private RelativeLayout re_shuizu_message;
	private RelativeLayout re_shuizu_all;
	private TextView tvTiezi;
	private ImageView img_all;
	public static LunTanDetailActivity activity;
	String position;
	int isbutton = 0;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		setContentView(R.layout.activity_luntan_homepage);
		activity = this;
		setStatusBarColor(R.color.home_blue);
		IntentFilter filter = new IntentFilter(CLOSELUNTANDETAIL);
		registerReceiver(broadcastReceiver, filter);
		// popupWindow.dismiss();
		position = getIntent().getStringExtra("position");
		System.out.println("positionpositionpositionpositionposition"
				+ position);
		arrayListForm = new ArrayList<LuntanForumBean.LuntanForumItemBean>();
		arrayListForm = (ArrayList<LuntanForumItemBean>) getIntent()
				.getSerializableExtra("list");
		if (arrayListForm == null)
			getShuiZuChildForum();
		else {
			initTabs();
		}
		// arrayListForm = App.arrayLisForumItemBeans;
		title.setText("水族论坛");

		onPinDaoGuanLi();
	}

	@Override
	protected void onSaveInstanceState(Bundle arg0) {
		// TODO Auto-generated method stub
		// super.onSaveInstanceState(arg0);
	}

	public void setCurrentPager(int cu) {
		viewpager.setCurrentItem(cu);
	}

	// PUPOwindow
	public void onCrePuPo() {
		View view = LayoutInflater.from(this).inflate(
				R.layout.popup_shuizu_more, null);
		re_shuizu_search = (RelativeLayout) view
				.findViewById(R.id.re_shuizu_search);
		re_shuizu_message = (RelativeLayout) view
				.findViewById(R.id.re_shuizu_message);
		re_shuizu_all = (RelativeLayout) view.findViewById(R.id.re_shuizu_all);
		tvTiezi = (TextView) view.findViewById(R.id.tvTiezi);
		img_all = (ImageView) view.findViewById(R.id.img_all);
		re_shuizu_search.setOnClickListener(this);
		re_shuizu_message.setOnClickListener(this);
		re_shuizu_all.setOnClickListener(this);
		popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);

		popupWindow.setBackgroundDrawable(new BitmapDrawable());
	}

	private void getShuiZuChildForum() {
		// TODO Auto-generated method stub
		MyJsonRequest.Builder<LuntanForumBean> builder = new MyJsonRequest.Builder<LuntanForumBean>()
				.typeKey("BY_BbsFavorite_query")
				.apiVer("100")
				.param("fup", "1")
				.param("uid",
						SPUtils.get(this, null, SPContants.USER_ID, "") + "")
				.requestListener(new XRequestListener<LuntanForumBean>() {

					@Override
					public void onResponse(LuntanForumBean orderBean) {//
						if (orderBean.getList() != null) {
							arrayListForm = orderBean.getList();
						}
						initTabs();
						// for (LuntanForumItemBean iterable_element :
						// orderBean.getList()) {
						// // App.arrayLisForumItemBeans.add(iterable_element);
						// //
						// System.out.println("-------------->>>"+iterable_element.getName());
						//
						// }
						// if (orderBean.getList() == null
						// || orderBean.getList().equals("null")) {
						// return;
						// } else {
						// System.out.println(arrayListForm.size()+">>");
						// arrayListForm = orderBean.getList();
						// ffid = arrayListForm.get(0).getFid();
						// initTabs();
						// }
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// Toast.makeText(LunTanDetailActivity.this, "msg" +
						// msg,
						// 0).show();
					}
				});
		MyJsonRequest<LuntanForumBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	@SuppressWarnings("deprecation")
	void initTabs() {
		MyFragment f1 = null;
		viewpager = (ViewPager) findViewById(R.id.viewpager);
		PagerAdapter pagerAdapter = new PagerAdapter(
				getSupportFragmentManager());
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		tabsAdapter = new ScrollTabsAdapter(this, arrayList);
		for (int i = 1; i <= arrayListForm.size(); i++) {
			// arrayList.add(R.drawable.tab + i);
			tabsAdapter.add(arrayListForm.get(i - 1).getName());
			f1 = new MyFragment(getIntent().getStringExtra("title"),
					arrayListForm.get(i - 1).getFid());
			pagerAdapter.addFragment(f1);
		}
		viewpager.setAdapter(pagerAdapter);
		viewpager.setCurrentItem(0);
		viewpager.addOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				ffid = arrayListForm.get(arg0).getFid();
				System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + ffid);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				ffid = arrayListForm.get(arg0).getFid();
				System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLwerwerwereLLLLL"
						+ arg0);
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		tabs.setViewPager(viewpager);
		tabs.setAdapter(tabsAdapter);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// pullDown();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.edit:
			LoginController.onFaTieClick(this, null);

		case R.id.shuizu_more:

			onRePupoDinw(v);

			break;
		case R.id.re_shuizu_search:
			Intent intent2 = new Intent(this, LunTanSearTableActivity.class);
			startActivityForResult(intent2, 103);
			popupWindow.dismiss();
			break;
		case R.id.re_shuizu_message:
			// Intent intent3 = new Intent(this, MyMessageActivity.class);
			// startActivity(intent3);
			LoginController.onPointMarketClick(LunTanDetailActivity.this, null);
			break;
		default:
			break;
		}

	}

	public void onLickiEditext() {

		Intent intent = new Intent(LunTanDetailActivity.this,
				RichTextActivity.class);
		// .putExtra("role", "modify");
		intent.putExtra("fid", ffid);
		intent.putExtra("list", arrayListForm);
		startActivity(intent);

	}

	public void onRePupoDinw(View v) {

		onCrePuPo();

		popupWindow.showAsDropDown(v);
		re_shuizu_all.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				LoginController.onAddShopCarClick(LunTanDetailActivity.this,
						null);
			}
		});
	}

	/***
	 * 查看精华帖
	 */

	public void onJinghuaTie() {
		if (isbutton == 0) {
			isbutton = 1;
			// refresh
			isJingHua = false;
			Intent intentw = new Intent("refreshisbuttn");
			intentw.putExtra("digest", isJingHua ? "1" : "0");
			sendBroadcast(intentw);
			tvTiezi.setText("精华");
			System.out.println("11111111111111111111111111111111111");
			img_all.setBackgroundResource(R.drawable.jing);
		} else {
			isJingHua = true;
			isbutton = 0;
			Intent intent = new Intent("refresh");
			intent.putExtra("digest", isJingHua ? "1" : "0");
			sendBroadcast(intent);
			img_all.setBackgroundResource(R.drawable.shuizu_all);
			System.out.println("22222222222222222222222222222222222222222222");
			tvTiezi.setText("全部");
		}
	}

	protected void pullUp() {
		MyJsonRequest.Builder<LunTanHomePageBean> builder = new MyJsonRequest.Builder<LunTanHomePageBean>()
				.param("fid", fid).apiVer("100").param("page_no", "" + pageNum)
				.param("stick", 0).typeKey("BY_ForumThread_query")
				.requestListener(new XRequestListener<LunTanHomePageBean>() {

					@Override
					public void onResponse(LunTanHomePageBean orderBean) {
						// onPullUpFinish(adapter, xlistview, orderBean);
						if (adapter == null) {
							adapter = new LunTanDetailAdapter(dataList,
									LunTanDetailActivity.this);
							xlistview.setAdapter(adapter);

						}

						if (orderBean.getCount() > 0) {
							dataList.addAll(orderBean.getList());
							adapter.notifyDataSetChanged();
						}

						pageNum++;
						xlistview.stopLoadMore();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						// onPullUpError(adapter, xlistview, exception, code,
						// msg);
					}
				});

		MyJsonRequest<LunTanHomePageBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	protected void pullUptwo(int digest) {
		MyJsonRequest.Builder<LunTanHomePageBean> builder = new MyJsonRequest.Builder<LunTanHomePageBean>()
				.param("fid", fid).apiVer("100").param("page_no", "" + pageNum)
				.param("stick", 0).typeKey("BY_ForumThread_query")
				.param("digest", digest)
				.requestListener(new XRequestListener<LunTanHomePageBean>() {

					@Override
					public void onResponse(LunTanHomePageBean orderBean) {
						// onPullUpFinish(adapter, xlistview, orderBean);
						if (detailAdapter == null) {
							detailAdapter = new LunTanTwoDetailAdapter(
									dataListtwo, LunTanDetailActivity.this);
							xlistview.setAdapter(detailAdapter);

						}

						if (orderBean.getCount() > 0) {
							dataList.addAll(orderBean.getList());
							adapter.notifyDataSetChanged();
						}

						pageNum++;
						xlistview.stopLoadMore();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						// onPullUpError(adapter, xlistview, exception, code,
						// msg);
					}
				});

		MyJsonRequest<LunTanHomePageBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);

		if (arg0 == 101 && arg1 == 102) {
			ArrayList<LuntanForumItemBean> arrayList = (ArrayList<LuntanForumItemBean>) arg2
					.getSerializableExtra("list");
			arrayListForm.clear();
			for (LuntanForumItemBean iterable_element : arrayList) {
				Log.v("title2", iterable_element.getName());
			}
			arrayListForm = new ArrayList<>();
			arrayListForm = arrayList;
			// tabs.removeAllViews();
			initTabs();
		}
		if (arg0 == 103 && arg1 == 104) {
			boolean isFind = false;
			String innerFid = arg2.getStringExtra("fid");
			for (int i = 0; i < arrayListForm.size(); i++) {
				if (innerFid.equals(arrayListForm.get(i).getFid())) {
					viewpager.setCurrentItem(i);
					isFind = true;
				}
			}
			if (!isFind) {
				ByAlert.alert("您还没有添加该论坛哦!");
			}

		}

	}

	public void onPinDaoGuanLi() {
		imgTop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// LoginController.onChangeForum(LunTanDetailActivity.this,
				// null);
				goToChangeForum();
			}
		});
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			finish();
		}
	};

	public void goToChangeForum() {
		Intent intent = new Intent(LunTanDetailActivity.this,
				LunTanPinDaoActivity.class);
		startActivity(intent);
	}

}
